package com.zr.sms.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import com.zr.sms.model.Employee;
import com.zr.sms.service.ChangePswService;
import com.zr.sms.serviceimpl.ChangePswServiceImpl;

public class ChangePswServlet extends HttpServlet {
	// 实例化员工修改密码对象
	ChangePswService chpsws = new ChangePswServiceImpl();

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// 设置字符编码为UTF-8
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		JSONObject jo = new JSONObject();
		PrintWriter pw = resp.getWriter();
		
		// 获取存储在session中的员工对象中的密码以及ID
		HttpSession session = req.getSession();
		Employee em = (Employee) session.getAttribute("currentemp");
		String epsw = em.getEpsw();
		int eid = em.getEid();
		// 获取用户修改密码输入框的值
		String oldepsw=(String) session.getAttribute("oldepsw");
		String npsw = req.getParameter("npsw");
		String npsw2 = req.getParameter("npsw2");
		if (oldepsw.equals(epsw)){//判断输入原密码是否正确
			if (npsw.length() == 0||npsw2.length() == 0) {//判断密码输入是否为空
				jo.put("msg1", 0);
				pw.write(jo.toString());
                                      } else {
                     if (npsw.equals(npsw2)) {// 判断两次输入新密码是否一致
				   // 密码修改后返回的结果：true成功；false失败。
				boolean a = chpsws.changeEpsw(npsw2, eid);
			    	if (a == true) {
					jo.put("msg2", 1);
					pw.write(jo.toString());
				 } else {
					jo.put("msg2", 0);
					pw.write(jo.toString());
				}
			} else {
				jo.put("msg2", 0);
				pw.write(jo.toString());
			}
		}
		}else {
			jo.put("msg1", 0);
			pw.write(jo.toString());
		}
	}

}
